package com.stgy.lease.web.api.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stgy.lease.model.domain.BrowsingHistory;
import com.stgy.lease.model.domain.GraphInfo;
import com.stgy.lease.web.api.dto.BaseSearchDto;
import com.stgy.lease.web.api.interceptor.StgyAuthInterceptor;
import com.stgy.lease.web.api.mapper.BrowsingHistoryMapper;
import com.stgy.lease.web.api.mapper.GraphInfoMapper;
import com.stgy.lease.web.api.service.BrowsingHistoryService;
import com.stgy.lease.web.api.service.GraphInfoService;
import com.stgy.lease.web.api.vo.HistoryItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author lingx
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2024-08-28 11:00:29
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Async
    @Override
    public void saveOrUpdateAsync(Long userId, Long id) {
        BrowsingHistory browsingHistory = this.getOne(Wrappers.lambdaQuery(BrowsingHistory.class)
                .eq(BrowsingHistory::getUserId, userId)
                .eq(BrowsingHistory::getRoomId, id)
                .last("limit 1"));
        if (browsingHistory == null) {
            browsingHistory = new BrowsingHistory();
            browsingHistory.setUserId(userId);
            browsingHistory.setRoomId(id);
        }
        //设置浏览时间
        browsingHistory.setBrowseTime(new Date());
        this.saveOrUpdate(browsingHistory);
    }

    //分页查询浏览记录
    @Override
    public Page<HistoryItemVo> pageItem(BaseSearchDto searchDto) {
        //分页查询 1对多 需要分布
        Page<HistoryItemVo> page = searchDto.getPage(HistoryItemVo.class);
        //需要使用会员id查询他自己的浏览器记录
        List<HistoryItemVo> historyItemVoList = baseMapper.selectPageItem(page, StgyAuthInterceptor.THREAD_LOCAL.get().getId());
        //查询每个浏览记录的房间图片列表
        historyItemVoList.forEach(historyItemVo -> {
            //查询每个浏览记录的房间图片列表
            List<GraphInfo> graphInfoList =
                    graphInfoMapper.selectByRoomId(historyItemVo.getRoomId());
            historyItemVo.setRoomGraphVoList(graphInfoList);
        });

        page.setRecords(historyItemVoList);
        return page;
    }
}